﻿using System;
using System.Collections;
using System.Collections.Generic;
using Assets.Scripts.NetFrame;
using Assets.Scripts.UserCache;
using DG.Tweening;
using ExitGames.Client.Photon;
using LitJson;
using PathologicalGames;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using WorldOfSuperpowers_COMMON;
using WorldOfSuperpowers_COMMON.DataModel;

public class MatchManager : MonoBehaviour
{
    public static MatchManager _instance;
    public ChooseSkillListContainer[] ChooseSkillListContainerArr = new ChooseSkillListContainer[2];
    public Dictionary<ushort,ChooseSkillListContainer> chooseSkillListContainerDic = new Dictionary<ushort, ChooseSkillListContainer>();
    #region  匹配相关对象

    public RectTransform MatchPanelRectTran;
    private Tween TranAlphaTween;
    private Tween TranMoveXTween;

    public Button MatchBtn;


    #endregion

    #region 敌对玩家信息
    public Image OppositeIcon;
    public Text OppositeLevel;
    public Text OppositeName;
    private GetToMatchModel model;
    #endregion

    private Text btnText;
    private SkillIconInfo[] AllSkillIconInfoArr;
    public Dictionary<ushort, ushort> skillID_IndexDic = new Dictionary<ushort, ushort>();


    public void Awake()
    {
        _instance = this;
        AddEventOnMatchBtn(MatchToGameBtn);
        btnText = MatchBtn.GetComponentInChildren<Text>();
        //此处获取全部技能数据
        GetAllSkillInfo();
        //初始化动画
        SetMacthPanelTween();
    }


    /// <summary>
    /// 开始匹配
    /// </summary>
    public void MatchToGameBtn()
    {
        //发送匹配消息给服务器
        Dictionary<byte,object> param = new Dictionary<byte, object>();
        param.Add((byte)OperationCode.Match,OperationCode.ReadyInMatchQueue);
        param.Add((byte)OperationCode.ReadyInMatchQueue, UserInfos.CurrentUserModel.UserAccount);
        PhotonPeerManager.GetInstance().SendMessage(OperationCode.Match, param);
    }

    /// <summary>
    /// 取消匹配
    /// </summary>
    public void DisMatchToGameBtn()
    {
        Dictionary<byte, object> param = new Dictionary<byte, object>();
        param.Add((byte)OperationCode.Match, OperationCode.DivideMatch);
        param.Add((byte)OperationCode.DivideMatch, UserInfos.CurrentUserModel.UserAccount);
        PhotonPeerManager.GetInstance().SendMessage(OperationCode.Match, param);
    }

    /// <summary>
    /// 发送当前选择给服务器
    /// </summary>
    public void ChooseSkillToServer()
    {
        Dictionary<byte, object> param = new Dictionary<byte, object>();
        param.Add((byte)OperationCode.Match,OperationCode.SkillID);
        SkillModel model = new SkillModel();
        model.MatchRoomIndex = UserInfos.MatchRoomIndex;
        model.userPos = UserInfos.MyMatchPos;
        model.skillID = SkillInfoWindowManager._instance.GetSkillIDToServer();
        print("本地方位:"+ model.userPos + "本次BP技能ID:"+ model.skillID);
        object content = ProtoTranslater.GetInstance().GetBytesFromType(model);
        param.Add((byte)OperationCode.SkillID, content);
        PhotonPeerManager.GetInstance().SendMessage(OperationCode.Match, param);
        ChangeMatchStatus(4);
    }

    /// <summary>
    /// 更改匹配状态
    /// </summary>
    public void ChangeMatchStatus(short matchStatus)
    {
        switch (matchStatus)
        {
            case 0:
                //进入匹配
                btnText.text = "取消匹配";
                AddEventOnMatchBtn(DisMatchToGameBtn);
                break;
            case 1:
                //取消匹配
                btnText.text = "开始匹配 ";
                AddEventOnMatchBtn(MatchToGameBtn);
                break;
            case 2:
                //Ban技能
                btnText.text = "禁用";
                AddEventOnMatchBtn(ChooseSkillToServer);
                break;
            case 3:
                //选择
                btnText.text = "选择";
                AddEventOnMatchBtn(ChooseSkillToServer);
                break;
            case 4:
                btnText.text = "等待对方选择";
                MatchBtn.onClick.RemoveAllListeners();
                SkillInfoWindowManager._instance.ResetSkillInfo();
                break;
        }
    }

    /// <summary>
    /// 显示非最后一次BP的上一次BP信息
    /// </summary>
    public void ShowBPInfo(bool IsBan,ushort[] skillIDs,bool currentIsBan)
    {
        for (ushort i = 0; i < skillIDs.Length; i++)
        {
            //检测是否没选择，没选择不处理
            if(skillIDs[i] == 10000) continue;
            //数组的下标代表方位，不是本地BP池的下标，通过数组下标定位BP池
            chooseSkillListContainerDic[i].AddChooseSkill(skillIDs[i],IsBan);
            MySkillPoolContainer._instance.FlagMyPoolIcon(skillIDs[i],IsBan);
        }
        ChangeMatchStatus(currentIsBan ? (short) 2 : (short) 3);
    }

    /// <summary>
    /// 最后一次BP信息
    /// </summary>
    /// <param name="IsBan"></param>
    /// <param name="skillIDs"></param>
    public void ShowBPInfo(bool IsBan,ushort[] skillIDs)
    {
        for (ushort i = 0; i < skillIDs.Length; i++)
        {
            //检测是否没选择，没选择不处理
            if (skillIDs[i] == 10000) continue;
            //数组的下标代表方位，不是本地BP池的下标，通过数组下标定位BP池
            chooseSkillListContainerDic[i].AddChooseSkill(skillIDs[i], IsBan);
            MySkillPoolContainer._instance.FlagMyPoolIcon(skillIDs[i], IsBan);
        }
        //进入倒计时10秒
        btnText.text = "准备开始游戏";
        MatchBtn.interactable = false;
        TipsController._instance.CountDown();
    }

    /// <summary>
    /// 给按钮添加点击事件
    /// </summary>
    /// <param name="BtnEvent"></param>
    public void AddEventOnMatchBtn(UnityAction BtnEvent)
    {
        print("切换匹配按钮事件");
        MatchBtn.onClick.RemoveAllListeners();
        MatchBtn.onClick.AddListener(BtnEvent);
    }

    /// <summary>
    /// 显示匹配界面,排列BP技能池
    /// </summary>
    public void ShowMatchPanel(GetToMatchModel model)
    {
        this.model = model;
        //对方匹配的位置ID
        UserInfos.OppositePos = model.userPos;
        //本方匹配的位置ID
        UserInfos.MyMatchPos = (ushort)(1 - model.userPos);
        print("本方位:"+ UserInfos.MyMatchPos + "准备就绪,对方方位:"+ UserInfos.OppositePos);
        UserInfos.MatchRoomIndex = model.RoomIndex;
        chooseSkillListContainerDic.Add(UserInfos.OppositePos, ChooseSkillListContainerArr[1]);
        chooseSkillListContainerDic.Add(UserInfos.MyMatchPos, ChooseSkillListContainerArr[0]);
        TranAlphaTween.PlayForward();
        SendReadyMessageToServer();
    }

    /// <summary>
    /// 显示敌对信息
    /// </summary>
    /// <param name="model"></param>
    public void ShowOppositeInfo(GetToMatchModel model)
    {
        //显示敌对玩家信息
        OppositeIcon.sprite = IconSpriteManager._instance.GetHeadIconFromIndex(model.IconIndex);
        OppositeLevel.text = model.oppositeNameLevel + "";
        OppositeName.text = model.oppositeName;
    }

    /// <summary>
    /// 发送准备消息给服务器，等待服务器返回进入BP阶段
    /// </summary>
    public void SendReadyMessageToServer()
    {
        Dictionary<byte,object> param = new Dictionary<byte, object>();
        //本机匹配方位
        ReadyForMatch rfm = new ReadyForMatch();
        rfm.MyMatchPos = UserInfos.MyMatchPos;
        rfm.MatchRoomIndex = UserInfos.MatchRoomIndex;
        param.Add((byte)OperationCode.Match,OperationCode.ReadyForMatch);
        object content = ProtoTranslater.GetInstance().GetBytesFromType(rfm);
        param.Add((byte)OperationCode.ReadyForMatch, content);
        //发送给服务器准备完成
        PhotonPeerManager.GetInstance().SendMessage(OperationCode.Match, param);

    }

    /// <summary>
    /// 获取全部技能信息
    /// </summary>
    public void GetAllSkillInfo()
    {
        string skillInfoStr = Resources.Load<TextAsset>("Skills/SkillList").text;
        AllSkillIconInfoArr = JsonMapper.ToObject<SkillIconInfo[]>(skillInfoStr);
        for (ushort i = 0; i < AllSkillIconInfoArr.Length; i++)
        {
            //将全部技能的ID与在这个数组各自对应的下标保存在字典中方便查找
            skillID_IndexDic.Add(AllSkillIconInfoArr[i].SkillID,i);
        }
    }

    /// <summary>
    /// 获取技能信息
    /// </summary>
    /// <param name="SkillID"></param>
    /// <returns></returns>
    public SkillIconInfo GetSkillInfo(ushort SkillID)
    {
        return AllSkillIconInfoArr[skillID_IndexDic[SkillID]];
    }

    /// <summary>
    /// 重置
    /// </summary>
    public void ResetMatchManager()
    {
        //chooseSkillListContainerDic.Clear();
        Dictionary<byte, object> param = new Dictionary<byte, object>();
        param.Add((byte)OperationCode.Match, OperationCode.BeginGame);
        PhotonPeerManager.GetInstance().SendMessage(OperationCode.Match, param);
        print("倒计时结束，游戏开始");
        EndAction();
    }

    public void EndAction()
    {
        //todo 进入下个场景加载界面
        //清理本界面全部东西
        MatchBtn.interactable = true;
        ChangeMatchStatus(1);
        //消除全部池实例对象
        //关闭界面
        TranAlphaTween.PlayBackwards();
        PoolManager.Pools["SkillIcon"].DespawnAll();
    }

    /// <summary>
    /// 初始化动画
    /// </summary>
    public void SetMacthPanelTween()
    {
        //匹配界面动画预设
        CanvasGroup cg = MatchPanelRectTran.GetComponent<CanvasGroup>();
        TranAlphaTween = cg.DOFade(1, 0.3f);
        TranAlphaTween.SetAutoKill(false);
        TranAlphaTween.SetEase(Ease.Linear);
        TranAlphaTween.Pause();

        TranMoveXTween = MatchPanelRectTran.DOAnchorPosX(-100, 0.3f);
        TranMoveXTween.SetRelative(true);
        TranMoveXTween.SetAutoKill(false);
        TranMoveXTween.SetEase(Ease.InOutCirc);
        TranMoveXTween.Pause();
        //界面透明时，关闭界面物体
        TranAlphaTween.OnStepComplete(delegate
        {
            if (TranAlphaTween.isBackwards)
            {
                MatchPanelRectTran.gameObject.SetActive(false);
            }
        });
        TranAlphaTween.OnPlay(delegate
        {
            if (!TranAlphaTween.isBackwards)
            {
                //界面显示时,开启界面物体,正序播放移动
                TranMoveXTween.PlayForward();
                MatchPanelRectTran.gameObject.SetActive(true);
                ShowOppositeInfo(model);
                //技能池中塞入当前账号已拥有的技能
                MySkillPoolContainer._instance.PutIconsInPool(UserInfos.CurrentUserModel.SkillArr); 
            }
            else
            {
                //界面透明动画前，逆序播放移动动画
                TranMoveXTween.PlayBackwards();
            }
        });
    }
}
